<template>
  <b-button icon="import" @click="onImport">导入</b-button>
  <Modal
    title="导入"
    :open="visible"
    :width="1100"
    :mask-closable="false"
    :keyboard="false"
    centered
    @cancel="onClose"
  >
    <Steps v-model:current="current" :items="items" class="w-[800px] mx-auto" />
    <template v-if="current === 0">
      <p class="text-center py-5">
        <span>请下载表格模板，在填写完成后，点击导入文件，完成文件上传</span>
      </p>
      <Flex justify="center">
        <Upload
          :custom-request="customRequest"
          @change="onChange"
          :accept="accept"
          :before-upload="onBeforeUpload"
          :showUploadList="false"
        >
          <div
            class="w-96 h-48 flex flex-col items-center justify-evenly rounded-sm border border-dashed"
          >
            <p class="text-center text-2xl">
              <CloudUploadOutlined
                :style="{ color: colorPrimary, fontSize: '80px' }"
              ></CloudUploadOutlined>
            </p>
            <p class="ant-upload-text">
              <span>将文件拖到此处，或</span
              ><a :style="{ color: colorPrimary }">点击上传</a>
            </p>
          </div>
        </Upload>
      </Flex>
      <p class="text-center py-5">
        <span
          >仅允许导入 xls、xlsx 格式文件。<a
            @click="onDownload"
            :style="{ color: colorPrimary, cursor: 'pointer' }"
            >下载模板</a
          ></span
        >
      </p>
    </template>
    <template v-else>
      <Result status="success" title="导入成功"></Result>
    </template>

    <template #footer>
      <template v-if="current === 1">
        <AButton @click="onClose">关闭</AButton>
      </template>
    </template>
  </Modal>
</template>
<script setup lang="tsx">
import { ref } from 'vue';
import {
  CheckOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons-vue';
import {
  Button as AButton,
  Flex,
  Modal,
  Result,
  Steps,
  type StepsProps,
  Upload,
  type UploadProps,
  message,
  theme,
} from 'ant-design-vue';
import { AxiosRequestConfig } from 'axios';

defineOptions({
  name: 'ImportModal',
});

const emits = defineEmits<{
  downloadTemplate: [];
  closed: [];
}>();

interface Props {
  uploadApi: (data: FormData, config: AxiosRequestConfig) => Promise<any>;
  accept: UploadProps['accept'];
}

const props = defineProps<Props>();

const { defaultAlgorithm, defaultSeed } = theme;
const { colorPrimary } = defaultAlgorithm(defaultSeed);

const current = ref<number>(0);
const visible = ref<boolean>(false);
const onImport = () => {
  visible.value = true;
};

const items: StepsProps['items'] = [
  {
    title: '下载模板',
    icon: <CloudDownloadOutlined />,
    disabled: true,
  },
  {
    title: '导入成功',
    icon: <CheckOutlined />,
    disabled: true,
  },
];

const onClose = () => {
  visible.value = false;
  current.value = 0;
  emits('closed');
};

const onDownload = () => {
  emits('downloadTemplate');
};

const onChange: UploadProps['onChange'] = (info) => {
  const { file } = info;
  if (file.status === 'done') {
    current.value = 1;
  }
};

const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  if (!props.accept?.includes(file.name.split('.').pop() || '')) {
    message.error(`仅支持${props.accept}类型文件`);
    return false;
  }
  return true;
};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append(filename || 'file', file);
  props
    .uploadApi(formData, {
      skipError: true,
      onUploadProgress: onProgress,
    })
    .then((res) => onSuccess?.(res.data))
    .catch((err) => {
      Modal.error({
        title: '提示',
        centered: true,
        content: err.message,
      });
      onError?.(err);
    });
};
</script>
